<?php

namespace app\sys\command;

use think\Db;
use think\console\Command;
use think\console\Input;
use think\console\Output;

// 定时任务 - 月度账单& todo关闭3个月人数不够的帮会   每月1号 00：10 计算
class MonthlyBill extends Command
{
    protected function configure()
    {
        $this->setName('monthly_bill')->setDescription('帮主月度账单 (帮会总销量 帮主收益)');
    }

    protected function execute(Input $input, Output $output)
    {
        $t1 = microtime(true);
        $output->writeln('================'.date('Y-m-d H:i:s').' Crontab job start================');

        $this->job();

        $t2 = microtime(true);
        $output->writeln('================'.date('Y-m-d H:i:s').' Crontab job end time_cost:'.round($t2 - $t1, 4).'ms================');
    }

    private function job()
    {
        //  帮主月度账单 (帮会总销量 帮主收益)
        $timestamp = time();
        $bt = strtotime(date('Y', $timestamp).'-'.(date('m', $timestamp) - 1).'-01');
        $firstday = date('Y-m-01', $bt);
        $et = strtotime("$firstday +1 month -1 day");
        $lastday = date('Y-m-d', $et);
        $time2wait = strtotime(date('Y-m-d 09:00:00')) - $timestamp;
        $wxgzh_service = new \wx\WxgzhService();
        $gang_list = Db::name('gang')->where(['disable' => 0])->select();
        foreach ($gang_list as $gang_info) {
            $gang_master_info = Db::name('user')->find($gang_info['user_id']);
            if ($gang_master_info['gzh_openid']) {
                $total_sale = Db::name('order')->where(['ct' => [['gte', $bt], ['lte', $et]], 'status' => 10, 'gang_id' => $gang_info['id']])->aggregate(['_id' => null,  'total_sale' => ['$sum' => '$gang_supply_cost']]);
                $total_redpacket = Db::name('red_packet')->where(['ct' => [['gte', $bt], ['lte', $et]], 'user_id' => $gang_info['user_id']])->aggregate(['_id' => null,  'total_redpacket' => ['$sum' => '$money']]);
                // 发送公众号模板消息（给帮主）早上9点推送
                $data = [
                    'first' => ['value' => '您的月度账单出炉啦！'],
                    'keyword1' => ['value' => $gang_master_info['name']],
                    'keyword2' => ['value' => $firstday.'至'.$lastday],
                    'keyword3' => ['value' => round($total_sale[0]['total_sale']).'元'],
                    'keyword4' => ['value' => round($total_redpacket[0]['total_redpacket']).'元'],
                    'remark' => ['value' => ''],
                ];
                $wxgzh_service->sendTemplateMsg($gang_master_info['gzh_openid'], 'AiPv1q5finTPmE-cVPgmGL2t1QmdQxH3OQt5omr25bk', $data, '/pages/index/welcome', $time2wait);
            }
        }
        //  生成业务员提成每月的第一条数据
        $cs_list = Db::name('admin')->where(['permission' => 3])->select();
        $rows = [];
        foreach ($cs_list as $data) {
            $rows[] = ['csid' => $data['id'], 'total' => 0.00, 'month' => $mstr, 'ct' => time()];
        }
        Db::name('cs_push_money')->insertAll($rows);
    }
}
